var PlayCanvas = new function(){

	var MAX_WIDTH = 1600;
	var MAX_HEIGHT = 1600;
	
	var width;
	var height;
	
	var director;
	var scene;
	var foregroundLayer;
	var centerLayer;
	var backgroundLayer;
	
	var offsetX;
	var offsetY;
	
	var loadedSprites = {};
	
	var Player;
	
	var play;
	
	var timestamp = new Date().getTime();
	
	var Collision;
	
	var DRAW_COLLISION = true;
	var ENHANCED_COLLISION = true;
	
	var keyLeft = false;
	var keyRight = false;
	var keyDown = false;
	var keyUp = false;
	
	this.init = function(debug){
	
		DRAW_COLLISION = debug;
	
		keyLeft = false;
		keyRight = false;
		keyDown = false;
		keyUp = false;
	
		Player = {};
		
		Collision = [];
		
		Player.vX = 0;
		Player.vY = 0;
		Player.aX = 0;
		Player.aY = 0;
		Player.x = 0;
		Player.y = 0;
		Player.offX = 0;
		Player.offY = 0;
		Player.onBox = false;
	
		offsetX = 0;
		offsetY = 0;
		
		width = $("#Creator_canvas").innerWidth();
		height = $("#Creator_canvas").innerHeight();
		
		director = new CAAT.Director().initialize(
			width,
			height,
			document.getElementById("Creator_canvas")
		);
		
		scene = director.createScene();
		
		bgImageLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		
		backgroundLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		centerLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		entityLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		foregroundLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
				
		scene.addChild(bgImageLayer);
		scene.addChild(backgroundLayer);
		scene.addChild(centerLayer);
		scene.addChild(entityLayer);
		scene.addChild(foregroundLayer);
		
		
		//director.loop(20);
		
		refresh();
		
		addListeners();
	};
	
	this.stop = function(){
		director.endLoop();
		director.destroy();
		play = false;
	};
	
	var addListeners = function(){
	
		//$("#Creator_canvas").keydown(function(e){
		$(document).on("keydown", function(e){
			$("#Creator_canvas").focus();
		});
		
		CAAT.registerKeyListener( function(key) {
			if (key.action=='down') {
				switch(key.keyCode){
					case 65:
					case 37: //left
						keyLeft = true;
						Player.actor.playAnimation("play").setImageTransformation(CAAT.Foundation.SpriteImage.TR_FLIP_HORIZONTAL);
						break;
					case 68:
					case 39: //right
						keyRight = true;
						Player.actor.playAnimation("play").setImageTransformation(CAAT.Foundation.SpriteImage.TR_NONE);
						break;
					case 87:
					case 38: //up
						keyUp = true;
						break;
					case 83:
					case 40: //down
						keyDown = true;
						break;
				}
			} else if (key.action=='up'){
				switch(key.keyCode){
					case 65:
					case 37: //left
						Player.actor.playAnimation("idle");
						keyLeft = false;
						break;
					case 68:
					case 39: //right
						Player.actor.playAnimation("idle");
						keyRight = false;
						break;
					case 87:
					case 38: //up
						keyUp = false;
						break;
					case 83:
					case 40: //down
						keyDown = false;
						break;
				}
			}
			H5.Log.debug("Action: " + key.action + " Key: " + key.keyCode, key);
		});
		
	};
	
	var refresh = function(){
	
		backgroundLayer.emptyChildren();
		centerLayer.emptyChildren();
		entityLayer.emptyChildren();
		foregroundLayer.emptyChildren();
		
		var images = {};
	
		for(var i = 0; i < WGC.data.sprite.length; i++){
			var s = WGC.data.sprite[i];
			if(s && !loadedSprites[s.spriteId])
				images[s.spriteId] = s.image;
		}
		
		H5.preloadImages(images, function(imgs){
				
			for(var i in imgs){
				var l = WGC.data.sprite[i].frames;
				var anim = [];
				for(var j = 1; j < l; j++){
					anim[j-1] = j;
				}
				
				loadedSprites[i] = new CAAT.SpriteImage().
							initialize(imgs[i], 1, WGC.data.sprite[i].frames).
							setChangeFPS(WGC.data.sprite[i].fps).
							addAnimation("idle", [0], 0).
							addAnimation("play", anim, 1000/WGC.data.sprite[i].fps);
							
				
			}
			
			var collisionTemp = [];
			
			for(var i = 0; i < WGC.data.gamebox.length; i++){
		
				var gb = WGC.data.gamebox[i];
				if(gb){
					var gbs = WGC.data.gameboxstate[gb.defaultStateId];
					if(gbs){
						var b = WGC.data.box[gbs.boxId];
						var s = WGC.data.sprite[b.spriteId];
						
						var actor = new CAAT.Actor().
								setBackgroundImage(loadedSprites[s.spriteId].getRef()).
								enableEvents(false).
								setPosition(gb.posX*16, gb.posY*16);
						
						switch(gb.gameBoxLayerId){
							case WGC.data.game.backgroundLayerId:
								backgroundLayer.addChild(actor);
								break;
							case WGC.data.game.centerLayerId:
								if(!collisionTemp[gb.posY]) collisionTemp[gb.posY] = [];
								collisionTemp[gb.posY][gb.posX] = true;
							
								centerLayer.addChild(actor);
								break;
							case WGC.data.game.foregroundLayerId:
								foregroundLayer.addChild(actor);
								break;
							default:
								break;
						}
						
					}
				}
			}
			for(var i = 0; i < WGC.data.gameentity.length; i++){
				var ge = WGC.data.gameentity[i];
				if(ge){
					var e = WGC.data.entity[ge.entityId];
					if(e){
						var es = WGC.data.entitystate[e.defaultStateId];
						var s = WGC.data.sprite[es.spriteId];
												
						Player.actor = new CAAT.Actor().
								setBackgroundImage(loadedSprites[s.spriteId].getRef()).
								enableEvents(false).
								setPosition(ge.posX - s.width/2, ge.posY - s.height/2).
								playAnimation("idle");
								
						Player.x = ge.posX;
						Player.y = ge.posY;
						Player.offX = s.width/2;
						Player.offY = s.height/2;
								
						entityLayer.addChild(Player.actor);
					}
				}
			}
			
			var cObj = {};
			var connect = false;
			
			for(var i = 0; i < collisionTemp.length; i++){
				if(collisionTemp[i]){
					for(var j = 0; j < collisionTemp[i].length; j++){
						if(collisionTemp[i][j]){
							if(!connect){
								cObj = {
									x: j*16,
									y: i*16,
									sX: 0,
									sY: 16,
								};
							}
							cObj.sX += 16;
							connect = true;
						} else {
							if(connect){
								Collision.push(cObj);
								cObj = {};
							}
							connect = false;
						}
					}
					if(connect){
						Collision.push(cObj);
						cObj = {};
					}
					connect = false;
				}
			}
			
			if(DRAW_COLLISION){
				for(var i = 0; i < Collision.length; i++){
					var c = Collision[i];
				
					var rect = new CAAT.ShapeActor().
							setLocation(c.x,c.y).
							setSize(c.sX,c.sY).
							setFillStyle('rgba(255,0,0,1.0)').
							setShape(CAAT.ShapeActor.prototype.SHAPE_RECTANGLE).
							setStrokeStyle('rgba(0,0,0,1)');
					entityLayer.addChild(rect);
				}
			}
			
		}, function(e){
			H5.Log.error(e);
		});
			
		timestamp = new Date().getTime();
		play = true;
		PlayCanvas.redraw();
	};
	
	this.redraw = function(){
	
		Player.vX = 0;
		if(keyLeft){
			Player.vX -= 10;
		}
		if(keyRight){
			Player.vX += 10;
		}
		
		if(keyUp && Player.onBox){
			Player.vY -= 36;
		}
	
		var time = new Date().getTime()
		var t = time - timestamp;
		
		t = t/100.
		
		timestamp = time;
		
		var totAY = - Player.aY + 9.81;
		
		Player.vX = Player.vX + Player.aX * t;
		Player.vY = Player.vY + totAY * t;
		
		var moveX = Player.vX * t;
		var moveY = Player.vY * t;
		
		var steps = 1;
		
		if(ENHANCED_COLLISION){
			if(Math.abs(moveX) > Math.abs(moveY)){
				steps = Math.ceil(Math.abs(moveX)/8.);
			} else {
				steps = Math.ceil(Math.abs(moveY)/8.);
			}
		}
		
		Player.onBox = false;
		
		for(var s = 0; s < steps; s++){
			Player.x = Player.x + (1.*moveX/steps);
			Player.y = Player.y + (1.*moveY/steps);
			
			
			for(var i = 0; i < Collision.length; i++){
				var c = Collision[i];
			
				if(!(
					Player.x + Player.offX < c.x ||
					Player.x - Player.offX > c.x + c.sX ||
					Player.y + Player.offY < c.y ||
					Player.y - Player.offY > c.y + c.sY
				)){
					var dX = (c.x + c.sX/2) - Player.x;
					var dY = (c.y + c.sY/2) - Player.y;
					
					var minX = c.sX/2 + Player.offX;
					var minY = c.sY/2 + Player.offY;
					
					
					
					if(minX - Math.abs(dX) <= minY - Math.abs(dY)){
						if(dX > 0){
							Player.x = Player.x - (minX - dX);
							Player.vX = 0;
						} else {
							Player.x = Player.x - (-minX - dX);
							Player.vX = 0;
						}
					} else {
						if(dY > 0){
							Player.onBox = true;
							Player.vY = 0;
							Player.y = Player.y - (minY - dY);
						} else {
							Player.vY = 0;
							Player.y = Player.y - (-minY - dY);
						}
					}
				}
			}
		}
	
		if(Player.actor)
			Player.actor.setPosition(Player.x - Player.offX, Player.y - Player.offY);
			
		offsetX = Player.x - width/2;
		offsetY = Player.y - height/2;
		
		if(offsetX < 0) offsetX = 0;
		if(offsetY < 0) offsetY = 0;
		
		
		if(offsetX > MAX_WIDTH - width) offsetX = MAX_WIDTH - width;
		if(offsetY > MAX_HEIGHT - height) offsetY = MAX_HEIGHT - height;
		
	
		backgroundLayer.setPosition(-offsetX, -offsetY);
		centerLayer.setPosition(-offsetX, -offsetY);
		entityLayer.setPosition(-offsetX, -offsetY);
		foregroundLayer.setPosition(-offsetX, -offsetY);
		
		
		director.loop(1);
		director.endLoop();
		
		if(play){
			setTimeout(function(){
				PlayCanvas.redraw();
			},25);
		}
	};
	
	
};